package com.hit.msmService.controller;

import com.hit.commonUtils.R;
import com.hit.commonUtils.RandomUtil;
import com.hit.msmService.service.MsmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/eduMsm/msm")
@CrossOrigin
public class MsmApiController {
    @Autowired
    private MsmService msmService;
    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    //发送短信
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone){
        //1 从redis获取验证码，如果获取到直接返回,防止重复调用
        String code1 = redisTemplate.opsForValue().get(phone);
        if(!StringUtils.isEmpty(code1)) {
            return R.ok();
        }

        //生成由阿里云发送的六位验证码
        String code= RandomUtil.getSixBitRandom();
        Map<String,Object> param=new HashMap<>();
        param.put("code",code);

        boolean isSend=msmService.send(param,phone);
        if(isSend) {
            //发送成功，把发送成功验证码放到redis里,设置有效时间
            redisTemplate.opsForValue().set(phone,code,5, TimeUnit.MINUTES);
            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }
    }
}
